<template>
  <div class="market-open-page">
    <div class="cnt">
      <div class="outer-box">
        <market-describe class="project-info" v-if="projectInfo" :itemInfo="projectInfo" :vipInfo="vipInfo" :dredge="dredge" :borderBottom="borderBottom"></market-describe>
      </div>
    <div class="vip-ad" @click="vipClickHandle">
      <img src="../../../../assets/img/market/vip-open.png" alt="">
    </div>
    <div class="price-title">请选择开通套餐</div>
    <market-priceSurface :priceList="priceList" :payInfo="priceSurfacePayInfo" :currAct='currPriceAct'
      @onVipClick="vipClickHandle"
      @couponClick="couponClickHandle"
      @priceItemClick="priceItemClickHandle"></market-priceSurface>
    </div>
   <div class="bottom">
    <div class="agreement-box">
      <span>点击立即支付，即表示已阅读并同意</span>
      <span class="agreement" @click="skipAgreement">《AW大师付费协议》</span>
    </div>
    <open-payment class="pay-submit-info" :isPayLoading="isPayLoading" :payInfo="submitPayInfo" @paySubmit="paySubmit"></open-payment>
   </div>
   <van-actionsheet v-model="showCoupon">
     <div class="coupon-box-cnt">
       <div class="coupon-title">
         <p class="title">请选择优惠券</p>
         <p class="tips">最多只能选择一张</p>
       </div>
       <div class="coupon-list">
         <div class="item" v-for="(item,index) in couponsList.page.records" :key="index" :class="{'active': currentCoupon==item}" @click="couponHander(item)">
           <div class="money">
             <p class="total">
               <span>￥</span><b>{{item.discountsLimit | numberFormatter}}</b>
             </p>
             <p class="tips">满{{item.satisfyLimit | numberFormatter}}元可用</p>
           </div>
           <div class="line"></div>
           <div class="info">
             <p class="name">{{item.couponsName}}</p>
             <p class="time">{{item.couponsStart}}-{{item.couponsEnd}}</p>
           </div>
           <div class="icon">
             <img src="../../../../assets/img/market/check1.png" alt="" v-if="currentCoupon == item">
             <img src="../../../../assets/img/market/check2.png" alt="" v-else>
           </div>
         </div>
       </div>
       <div class="action-btn" @click="chooseCoupon">确定</div>
     </div>
   </van-actionsheet>
  </div>
</template>
<script>
import marketService from 'SERVICE/marketService'
import commonService from 'SERVICE/commonService'
import userService from 'SERVICE/userService'
import mycoupons from 'SERVICE/mycoupons'
import MarketDescribe from 'COMP/MarketDescribe/'
import MarketPriceSurface from 'COMP/MarketPriceSurface/'
import OpenPayment from 'COMP/OpenPayment/'
import { mapGetters } from 'vuex'
import * as types from '@/store/mutation-types'
export default {
  components: {
    MarketDescribe,
    MarketPriceSurface,
    OpenPayment
  },
  created() {
    this.linkerId = this.$route.params.id
    this.newChannelId = this.$route.params.newChannelId || ''
    // if (this.marketOpenCache && this.marketOpenCache.linkerId && this.marketOpenCache.linkerId == this.linkerId) {
    //   this.priceList = this.marketOpenCache.priceList
    //   this.projectInfo = this.marketOpenCache.projectInfo
    //   this.initSelectedInfo()
    //   return
    // }
    this.init()
    this.getVipInfo()
  },
  data: () => ({
    currPriceAct: 0,
    costType: 2, //1、开通vip 2、楼盘开通 3：套盘套餐开通 4：一天体验
    isPayLoading: false,
    linkerId: '',
    projectInfo: null,
    priceList: [],
    priceSurfacePayInfo: { balanceAmount: 0, balancePay: 0, coupon: 0, isShowCoupon: false },
    currPriceListIndex: 0,
    submitPayInfo: { value: 0, coupon: 0 },
    describeInfo: [{ dredgeFlag: false, borderBottom: false }],
    show: false,
    dredge: false,
    userPrice: 0,
    borderBottom: false,
    vipInfo: {},
    newChannelId: '',
    showCoupon: false,
    couponsList: {page:{}},
    currentCoupon: ''
  }),
  computed: {
    ...mapGetters(['userInfo', 'marketOpenCache', 'currSelectedCoupon'])
  },
  methods: {
    // 获取VIP详情
    async getVipInfo() {
      let res = await marketService.vipInfo()
      this.vipInfo = res || {}
    },
    async init() {
      this.userPrice = this.userInfo.price
      this.getUserInfo()
      this.getLinkerAmountList()
      this.getMarketDescribeInfo()
    },
    async getUserInfo() {
      const res = await userService.getUserInfo()
      this.userPrice = res.price
      // this.$store.dispatch('userInfo', Object.assign(this.userInfo, { price: res.price }))
    },
    skipAgreement() {
      this.$router.push('/open/agreement')
    },
    vipClickHandle() {
      this.$router.push('/user/myMember')
    },
    async initSelectedInfo() {
      let couponStr = ''
      let priceItem = this.priceList[this.marketOpenCache.currPriceListIndex]
      let balancePay = 0
      this.currPriceAct = this.marketOpenCache.currPriceListIndex
      let submitPrice = priceItem.subscribeAmount
      let coupon = 0

      await this.getUserInfo()
      if (this.marketOpenCache && this.marketOpenCache.currSelectedCoupon) {
        this.priceSurfacePayInfo = { balanceAmount: this.userPrice, balancePay: 0, coupon: 0 }
        let currCunpon = this.marketOpenCache.currSelectedCoupon
        if (currCunpon.type == 20) {
          let couponValue = Number(priceItem.subscribeAmount) * Number(1 - currCunpon.discountsLimit / 10)
          submitPrice = submitPrice - couponValue
          couponStr = '-¥ ' + parseFloat(couponValue / 100).toFixed(2)
          coupon = couponValue
        } else {
          couponStr = '-¥ ' + parseFloat(currCunpon.discountsLimit).toFixed(2)
          submitPrice = submitPrice - currCunpon.discountsLimit * 100
          coupon = currCunpon.discountsLimit * 100
        }
        this.priceSurfacePayInfo = Object.assign(this.priceSurfacePayInfo, { coupon: couponStr, isShowCoupon: true })
      } else {
        if (this.marketOpenCache.projectCoupons) {
          let couponStr = this.marketOpenCache.projectCoupons.length + '张可用'
          this.priceSurfacePayInfo = Object.assign(this.priceSurfacePayInfo, { coupon: couponStr, isShowCoupon: true })
        } else {
          this.priceSurfacePayInfo = Object.assign(this.priceSurfacePayInfo, { isShowCoupon: false })
        }
      }

      submitPrice = submitPrice - this.userPrice
      balancePay = this.userPrice
      if (submitPrice < 0) {
        balancePay = this.userPrice + submitPrice
        submitPrice = 0
      } else {
        if (balancePay > this.userPrice) {
          balancePay = this.userPrice
          submitPrice = balancePay - this.userPrice
        }
      }
      balancePay = balancePay < 0 ? (balancePay = 0) : balancePay
      this.submitPayInfo = { value: submitPrice, coupon: coupon }
      this.priceSurfacePayInfo = Object.assign(this.priceSurfacePayInfo, { balanceAmount: this.userPrice, balancePay: balancePay })
    },
    priceItemClickHandle(index) {
      this.$store.commit(types.SET_MARKET_OPEN_CACHE, Object.assign(this.marketOpenCache, { currPriceListIndex: index }))
      this.currPriceAct = index
      this.priceSurfacePayInfo = { balanceAmount: this.userPrice, balancePay: 0, coupon: 0 }
      this.currPriceListIndex = index
      let priceItem = this.priceList[this.currPriceListIndex]
      let submitPrice = priceItem.subscribeAmount
      if (submitPrice < 0) submitPrice = 0
      let balancePay = 0
      submitPrice = submitPrice - this.userPrice
      balancePay = this.userPrice
      if (submitPrice < 0) {
        submitPrice = 0
        balancePay = priceItem.subscribeAmount
      }

      this.submitPayInfo = { value: submitPrice, coupon: 0 }
      this.priceSurfacePayInfo = Object.assign(this.priceSurfacePayInfo, { balancePay: balancePay })
      this.getCoupan()
    },
    couponHander (item) {
      if (this.currentCoupon == item) {
        this.currentCoupon = ''
      } else {
        this.currentCoupon = item
      }
    },
    couponClickHandle() {
      // this.$router.push('/market/couponSelect/' + this.linkerId)
      this.showCoupon = true
    },
    // 选择优惠券
    chooseCoupon () {
      this.$store.commit(types.SET_MARKET_OPEN_CACHE, Object.assign(this.marketOpenCache, { currSelectedCoupon: this.currentCoupon }))
      this.initSelectedInfo()
      this.showCoupon = false
    },
    async getCoupan() {
      let priceItem = this.priceList[this.currPriceListIndex]
      let res = await mycoupons.getMyCoupons(this.linkerId, priceItem.subscribeAmount, 1, 1000)
      this.couponsList = res
      let couponStr = res.canUseNum + '张可用'
      this.priceSurfacePayInfo = Object.assign(this.priceSurfacePayInfo, { coupon: couponStr, isShowCoupon: res.canUseNum > 0 ? true : false })
      // this.$store.dispatch('setProjectCoupons', res.page.records)
      this.$store.commit(types.SET_MARKET_OPEN_CACHE, Object.assign(this.marketOpenCache, { projectCoupons: res.page.records }))
    },

    async paySubmit() {
      let priceItem = this.priceList[this.marketOpenCache.currPriceListIndex]
      let param = {
        linkerId: this.linkerId,
        linkerName: this.projectInfo.linkerName,
        costType: this.costType, //1、开通vip 2、楼盘开通 3：套盘套餐开通 4：一天体验
        subscribeNum: priceItem.subscribeNum,
        amountId: priceItem.id,
        payOpenid: this.userInfo.payOpenId,
        channelId: this.newChannelId
      }
      console.log('pay')
      if (this.marketOpenCache.currSelectedCoupon) {
        param.couponsCodes = this.marketOpenCache.currSelectedCoupon.couponsCode
      }
      this.isPayLoading = true
      const res = await commonService.payForProject(param)
      const purchaseId = res.purchaseId
      this.isPayLoading = false
      if (res.prepayStatus) {
        if (res.isPay) {
          wx.chooseWXPay({
            //弹出支付
            timestamp: res.timestamp,
            nonceStr: res.nonceStr,
            package: res.packageId,
            signType: 'MD5',
            paySign: res.signature,
            success: res => {
              this.paySuss()
            },
            cancel: res => {
              this.$toast('支付取消')
              this.cancelPayment(purchaseId)
            },
            fail: res => {
              this.$toast('支付失败')
              this.cancelPayment(purchaseId)
            }
          })
        } else {
          this.paySuss()
        }
      } else {
        this.$toast('支付失败')
      }
    },

    cancelPayment(purchaseId) {
      commonService.cancelPayment(purchaseId)
    },
    
    // 免费楼盘付费渠道切换渠道
    switchChannel () {
      marketService.switchChannel({
        linkerId:  this.linkerId,
        newChannelId: this.newChannelId,
        oldChannelId: '',
        switchingReason: ''
      }).then(res => {}).catch()
    },

    paySuss() {
      let _pirce = this.userPrice - this.priceSurfacePayInfo.balancePay
      let data = Object.assign({},this.userInfo,{ price: _pirce })
      this.$store.commit(types.USER_INFO, data)
      this.getMarketDescribeInfo()
      this.getLinkerAmountList()
      // 免费楼盘付费渠道切换渠道
      if (this.$route.params.newChannelId) {
        this.switchChannel()
      }
      window.sessionStorage.setItem("marketChange", true)
      this.$dialog
        .confirm({
          title: '开通成功',
          message: '你已成功开通楼盘' + '，快去推荐给身边的小伙伴',
          cancelButtonText: '取消',
          className: 'success-hint'
        })
        .then(() => {
          // 改变缓存数据状态
          if (window.sessionStorage.getItem('marketList')) {
            let data = JSON.parse(window.sessionStorage.getItem('marketList'))
            data.marketList.forEach(el => {
              if(el.linkerId === this.linkerId) {
                el.openStatus = 2
                el.expireDate = this.projectInfo.expireDate,
                el.expireTime = this.projectInfo.expireTime,
                el.invalidTimeStr = this.projectInfo.expireTime,
                el.openTimes += 1
                el.openStatus = 2
              }
            })
            window.sessionStorage.setItem('marketList',JSON.stringify(data))
          }
          this.$router.replace('/market/' + this.linkerId)
        })
        .catch(async () => {
          await this.getUserInfo()
          this.priceSurfacePayInfo = Object.assign(this.priceSurfacePayInfo, { balanceAmount: this.userPrice })
        })
    },

    async getMarketDescribeInfo() {
      const res = await marketService.getLinkerSimpleDetail(this.linkerId)
      console.log(res, '开通数据', res.city, res.district)

      this.projectInfo = {
        linkerImg: res.headImgUrl,
        linkerAddress: `${res.city} ${res.county}`,
        city: res.city,
        district: res.district,
        linkerTags: res.projectTagList,
        linkerPrice: res.averagePrice,
        linkerName: res.linkerName,
        openTimes: res.openTimes,
        sale: res.sale,
        commission: res.commission,
        saleStatus: res.saleStatus,
        expireTime: res.expireTime,
        expireDate: res.expireDate
      }
      this.$store.commit(types.SET_MARKET_OPEN_CACHE, Object.assign(this.marketOpenCache, { linkerId: this.linkerId, projectInfo: this.projectInfo }))
    },
    async getLinkerAmountList() {
      const res = await marketService.getLinkerAmountList(this.linkerId)
      this.priceList = res
      this.$store.commit(types.SET_MARKET_OPEN_CACHE, Object.assign(this.marketOpenCache, { priceList: this.priceList }))
      this.priceItemClickHandle(0)
    }
  }
}
</script>
<style lang="less">
.market-open-page {
  width: 100%;
  height: 100%;
  background: #f7f9fa;
  display: flex;
  flex-direction: column;
  .cnt{
    flex: 1;
    overflow-y: auto;
  }
  .bottom{
    height: 102px;
    border-top:10px solid #F2F4F5;
  }
  .outer-box{
    background:rgba(255,255,255,1);
    padding: 24px 16px 16px;
    .scale-1px-bottom:after{
      height: 0;
    }
    .project-info{
      box-shadow:0px 2px 4px 0px rgba(206,209,214,0.41);
      border-radius:6px;
      border:1px solid rgba(206,209,214,0.5);
    }
  }
  .vip-ad{
    padding: 0 14px;
    height: 64px;
    background-color: #fff;
  }
  .price-title{
    font-size:18px;
    font-family:'PingFangSC';
    font-weight:600;
    color:rgba(51,51,51,1);
    line-height:26px;
    padding: 20px 16px 14px;
    background-color: #fff;
  }
  .pay-submit-info {
    height: 60px;
  }
  .agreement-box {
    background-color: #fff;
    height: 32px;
    padding-left: 16px;
    display: flex;
    align-items: center;
    span {
      font-size: 10px;
      font-weight: 400;
      color: rgba(153, 153, 153, 1);
    }
    .agreement {
      font-size: 10px;
      font-weight: 400;
      color: #007ae6;
    }
  }
  .coupon-box-cnt{
    font-family:'PingFangSC';
    max-height: 500px;
    font-size: 16px;
    display: flex;
    flex-direction: column;
    .coupon-title{
      padding: 24px 16px 16px;
      .title{
        height:26px;
        font-size:18px;
        font-weight:600;
        color:rgba(51,51,51,1);
        line-height:26px;
      }
      .tips{
        height:16px;
        font-size:12px;
        font-weight:400;
        color:rgba(102,102,102,1);
        line-height:16px;
      }
    }
    .coupon-list{
      margin: 0 16px;
      overflow-y: scroll;
      .item{
        display: flex;
        align-items: center;
        height:90px;
        background:rgba(255,255,255,1);
        box-shadow:0px 3px 6px 0px rgba(58,76,130,0.07),0px 2px 17px 0px rgba(34,47,85,0.05);
        margin-bottom: 16px;
        border-radius: 6px;
        border:1px solid #f1f1f1;
        .money{
          width: 90px;
          flex-basis: 90px;
          text-align: center;
          .total{
            color: #007AE6;
            span{
              font-size: 14px;
            }
            b{
              font-size: 22px;
            }
          }
          .tips{
            font-size: 10px;
            color: #666;
          }
        }
        .line{
          width:2px;
          height:43px;
          background-color: #F1F1F1;
        }
        .info{
          flex: 1;
          margin-left: 15px;
          .name{
            font-size: 16px;
            color: #333;
            line-height:24px;
            font-weight: 600;
          }
          .time{
            font-size: 10px;
            color: #9CA5B5;
            line-height:14px;
          }
        }
        .icon{
          width: 46px;
          img{
            width: 22px;
            height: 22px;
          }
        }
        &.active{
          color: #007AE6;
          background:rgba(250,253,255,1);
          box-shadow:0px 3px 6px 0px rgba(0,122,230,0.07),0px 2px 17px 0px rgba(0,122,230,0.05);
          border-color: rgba(0,122,230,1);
          .money{
            .tips{
              color: #007AE6;
            }
          }
          .info{
            .name,.time{
              color: #007AE6;
            }
          }
        }
      }
    }
    .action-btn{
      margin: 16px;
      height:44px;
      background:#007AE6;
      border-radius:6px;
      line-height: 44px;
      color: #fff;
      font-size: 16px;
      text-align: center;
    }
  }
}
.success-hint {
  width: 290px;
  height: 160px;
  background: rgba(255, 255, 255, 1);
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  .van-dialog__header {
    font-size: 18px;

    font-weight: 600;
    color: rgba(51, 51, 51, 1);
    padding-top: 16px;
  }
  .van-dialog__message--has-title {
    font-size: 15px;
    line-height: 1.5 !important;
    font-weight: 400;
    color: rgba(51, 51, 51, 1);
    text-align: center;
    width: 253px;
    padding: 0;
    margin: 9px 0 15px 15px;
  }
  .van-dialog__footer--buttons {
    flex: 1;
    .van-hairline--left {
      color: rgba(0, 122, 230, 1);
    }
  }
}
</style>
